package hephaestus.common;

import java.net.*;
import java.io.*;

/**
 * Simple wrapper for Socket objects
 * TODO: Make networking NIO based, good grief! - OM
 * @author Oliver Maskery
 */
public class Connection {
	private BufferedReader input;
	private PrintWriter output;
	private Socket socket;
	
	public Connection(Socket socket) throws IOException
	{
		input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		output = new PrintWriter(socket.getOutputStream(), true);
		this.socket = socket;
	}
	
	public String getIP()
	{
		return socket.getInetAddress().getHostAddress();
	}
	
	public void send(String text)
	{
		output.write(text + "\r\n");
		output.flush(); // is this needed? I think so... - OM
	}
	
	public void setTimeout(int milliseconds) throws SocketException
	{
		socket.setSoTimeout(milliseconds);
	}
	
	public String receive() throws IOException
	{
		try
		{
			return input.readLine();
		}
		catch(SocketTimeoutException e)
		{
			return null;
		}
	}
	
	public void close() throws IOException
	{
		output.close();
		input.close();
		socket.close();
	}
}
